package com.weakteam.orderonline.dataresource.dao;

import com.weakteam.orderonline.dataresource.domain.Menu;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

/**
 * @author Nail
 */

@Repository
public class MenuDAOImpl implements MenuDAO {

    @PersistenceContext
    private EntityManager em;

    @Override
    public List<Menu> getAll() {
        return em.createQuery("FROM Menu m ORDER BY m.order").getResultList();
    }

    @Override
    public List<Menu> getAllEnabled() {
        return em.createQuery("FROM Menu m WHERE m.enabled = true ORDER BY m.order").getResultList();
    }

    @Override
    public Menu getById(Integer id) {
        return em.find(Menu.class, id);
    }

    @Override
    public void save(Menu menu) {
        this.em.merge(menu);
    }

    @Override
    public boolean delete(Integer id) {
        final String query = "DELETE Menu m WHERE m.id = :id";
        int count = em.createQuery(query).setParameter("id", id).executeUpdate();
        return (count > 0);
    }

    @Override
    public Integer getMaxOrder() {
        final String query = "SELECT max(m.order) AS max FROM Menu m";
        Integer maxOrder = (Integer)em.createQuery(query).getSingleResult();
        if (maxOrder==null) maxOrder = 0;
        return maxOrder;
    }

    @Override
    public List<String> getImageFileList() {
        final String query = "SELECT distinct(m.image) AS img FROM Menu m WHERE m.image IS NOT null and m.image != 'null'";
        List<String> result = (List<String>)em.createQuery(query).getResultList();
        return result;
    }

    @Override
    public List<String> getIcoFileList() {
        final String query = "SELECT distinct(m.ico) AS img FROM Menu m WHERE m.ico IS NOT null and m.ico != 'null'";
        List<String> result = (List<String>)em.createQuery(query).getResultList();
        return result;
    }

    @Override
    public List<String> getEnabledImageFileList() {
        final String query = "SELECT distinct(m.image) AS img FROM Menu m WHERE m.enabled = true and m.image IS NOT null and m.image != 'null'";
        List<String> result = (List<String>)em.createQuery(query).getResultList();
        return result;
    }

    @Override
    public List<String> getEnabledIcoFileList() {
        final String query = "SELECT distinct(m.ico) AS img FROM Menu m WHERE m.enabled = true and m.ico IS NOT null and m.ico != 'null'";
        List<String> result = (List<String>)em.createQuery(query).getResultList();
        return result;
    }
}
